package com.itheima.tanhuauser.interceptor;

import com.alibaba.fastjson.JSON;

import com.itheima.exception.TokenException;
import com.itheima.pojo.User;
import com.itheima.tanhuauser.thread.TokenThread;
import com.itheima.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {


    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("请求路径{}",request.getRequestURI());
        String token = request.getHeader("Authorization");
        //判断拿到的token是否为一个正常的字符串，否则抛出异常
        if (!StringUtils.hasText(token)){
            throw new TokenException();
        }
        //获取redis中生成的token
        String employee = (String) redisTemplate.opsForValue().get("user_token:" + token);
        if (!StringUtils.hasText(employee)){
            throw new TokenException();
        }
        //将字符串转换为对象
        UserVo byToken = JSON.parseObject(employee, UserVo.class);
        if (byToken==null){
            throw new TokenException();
        }

        String id = byToken.getId();
        //把用户信息写入到ThreadLocal里面
        TokenThread.set(id);
        return true;
    }
}
